package com.homework.week5_2.dao;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.sql.DataSource;
import java.sql.*;

@Component
public class Jdbc {

    @Autowired
    private DataSource dataSource;

    public void contextLoads() throws SQLException {
        // 查看默认的数据源 ：class com.zaxxer.hikari.HikariDataSource
        System.out.println(dataSource.getClass());
        // 获得数据库连接
        Connection connection = dataSource.getConnection();
        // 查看获得的连接 HikariProxyConnection@354350463 wrapping com.mysql.cj.jdbc.ConnectionImpl@10895b16
        // 是 JDBC 的连接！
        System.out.println(connection);
        connection.close();
    }

    public void jdbc() throws ClassNotFoundException, SQLException {
        Class.forName("com.mysql.cj.jdbc.Driver") ;
        String url = "jdbc:mysql://localhost:3306/sys?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8";
        Connection conn = DriverManager.getConnection(url,"root","root");
        Statement st = conn.createStatement() ;
        ResultSet rs = st.executeQuery("SELECT * FROM sys_config") ;
        while(rs.next()){
            String variable = rs.getString("variable") ;
            String value = rs.getString("value") ; // 此方法比较高效
            String res = "variable:"+variable+",value:"+value;
            System.out.println(res);
        }
        if(rs != null){   // 关闭结果集
            try{
                rs.close() ;
            }catch(SQLException e){
                e.printStackTrace() ;
            }
        }
        if(st != null){   // 关闭声明
            try{
                st.close() ;
            }catch(SQLException e){
                e.printStackTrace() ;
            }
        }
        if(conn != null){  // 关闭连接对象
            try{
                conn.close() ;
            }catch(SQLException e){
                e.printStackTrace() ;
            }
        }

    }


}
